<template>
	<view class="water-info-container">
		<!-- 顶部数据卡片 -->
		<view class="top-data-section">
			<view class="main-data">
				<view class="main-header">
					<view class="level-column">
						<view class="value-with-unit">
							<text class="main-value">{{ formatLevel(latestInfo?.rz) }}</text>
							<text class="main-unit">m</text>
						</view>
						<view class="badge-row">
							<view class="badge badge-rise">
								<text class="badge-icon">兴</text>
							</view>
							<view class="badge badge-rise">
								<text class="badge-value">{{ riseBadgeValue }}</text>
							</view>
							<view class="badge" :class="statusBadgeClass">
								<text class="badge-text">{{ statusText }}</text>
							</view>
						</view>
					</view>

					<view class="meta-column">
						<view class="meta-row">
							<text class="meta-label">时间</text>
							<text class="meta-value">{{ latestInfo?.tm || '--' }}</text>
						</view>
						<view class="meta-row">
							<text class="meta-label">正常高水位</text>
							<text class="meta-value">{{ formatLevel(normalHighLevel) }}</text>
							<text class="small-unit"> m</text>
						</view>
					</view>
				</view>

				<view class="data-grid two-col">
					<view class="data-row">
						<text class="label">入库</text>
						<view class="value-inline">
							<text class="value">{{ formatFlow(latestInfo?.inq) }}</text>
							<text class="small-unit"> m³/s</text>
						</view>
						<text class="label">日均入库</text>
						<view class="value-inline">
							<text class="value">{{ formatFlow(latestInfo?.avinq) }}</text>
							<text class="small-unit"> m³/s</text>
						</view>
					</view>
					<view class="data-row">
						<text class="label">出库</text>
						<view class="value-inline">
							<text class="value">{{ formatFlow(latestInfo?.otq) }}</text>
							<text class="small-unit"> m³/s</text>
						</view>
						<text class="label">日均出库</text>
						<view class="value-inline">
							<text class="value">{{ formatFlow(latestInfo?.avotq) }}</text>
							<text class="small-unit"> m³/s</text>
						</view>
					</view>
					<view class="data-row">
						<text class="label">蓄量</text>
						<view class="value-inline">
							<text class="value">{{ formatStorage(latestInfo?.w) }}</text>
							<text class="small-unit"> 10⁶m³</text>
						</view>
						<text class="label">防洪剩余</text>
						<view class="value-inline">
							<text class="value">{{ formatStorage(latestInfo?.remain_w) }}</text>
							<text class="small-unit"> 10⁶m³</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 水情图标签栏 -->
		<view class="tab-section">
			<view class="tab-bar">
				<view class="tab-item" :class="{ active: activeTab === 'chart' }" @click="activeTab = 'chart'">
					<text class="tab-text">水情图</text>
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'main' }" @click="activeTab = 'main'">
					<text class="tab-text">主水库</text>
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'updown' }" @click="activeTab = 'updown'">
					<text class="tab-text">上下游水库</text>
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'river' }" @click="activeTab = 'river'">
					<text class="tab-text">河道断面</text>
				</view>
			</view>
		</view>

		<!-- 水情图（地图） -->
		<view class="chart-section" v-show="activeTab === 'chart'">
			<LeafletMap
				ref="leafletMapRef"
				map-id="water-chart-map"
				:center="[40.25, 122.7]"
				:zoom="8"
				:auto-init="activeTab === 'chart'"
				@map-ready="handleMapReady"
			/>
		</view>

		<!-- 主水库标签页内容 -->
		<view class="main-reservoir-section" v-if="activeTab === 'main'">
			<!-- 时间选择区域 -->
			<view class="simple-date-bar">
				<DateTimePicker 
					v-model="mainStartDate"
					:defaultDaysOffset="-7"
					@change="handleMainDateChange"
				/>
				<text class="date-separator">至</text>
				<DateTimePicker 
					v-model="mainEndDate"
					:defaultDaysOffset="0"
					@change="handleMainDateChange"
				/>
			</view>

		<!-- 水情情势卡片 -->
		<view class="water-situation-card">
			<text class="situation-title">水情情势</text>
			<view class="situation-grid">
				<view class="situation-item">
					<text class="situation-label">总雨量</text>
					<view class="situation-value-row">
						<text class="situation-value">{{ currentSituation.sum_rain }}</text>
						<text class="situation-unit">mm</text>
					</view>
				</view>
				<view class="situation-item">
					<text class="situation-label">总入库</text>
					<view class="situation-value-row">
						<text class="situation-value">{{ currentSituation.sum_inq }}</text>
						<text class="situation-unit">×10⁶m³</text>
					</view>
				</view>
				<view class="situation-item">
					<text class="situation-label">总出库</text>
					<view class="situation-value-row">
						<text class="situation-value">{{ currentSituation.sum_otq }}</text>
						<text class="situation-unit">×10⁶m³</text>
					</view>
				</view>
			</view>
		</view>

			<!-- 该小时水情 -->
			<view class="hour-water-info-card">
				<view class="hour-header-row">
					<text class="hour-title">该小时水情</text>
					<text class="hour-time">{{ currentHourTime }}</text>
					<view class="export-btn">
						<text class="export-icon">📋</text>
					</view>
				</view>
			<view class="hour-data-grid">
				<view class="hour-item">
					<text class="hour-value-text">{{ currentHourData.rainfall }}</text>
					<view class="hour-label-wrapper">
						<text class="hour-label-text">降雨</text>
						<text class="hour-unit-text">(mm)</text>
					</view>
				</view>
				<view class="hour-item">
					<text class="hour-value-text">{{ currentHourData.inflow }}</text>
					<view class="hour-label-wrapper">
						<text class="hour-label-text">入库流量</text>
						<text class="hour-unit-text">(m³/s)</text>
					</view>
				</view>
				<view class="hour-item">
					<text class="hour-value-text">{{ currentHourData.outflow }}</text>
					<view class="hour-label-wrapper">
						<text class="hour-label-text">出库流量</text>
						<text class="hour-unit-text">(m³/s)</text>
					</view>
				</view>
				<view class="hour-item">
					<text class="hour-value-text">{{ currentHourData.waterLevel }}</text>
					<view class="hour-label-wrapper">
						<text class="hour-label-text">库水位</text>
						<text class="hour-unit-text">(m)</text>
					</view>
				</view>
			</view>
			</view>

		<!-- 图表区域 -->
		<view class="main-chart-container">
			<view 
				class="chart-canvas-wrapper"
				@touchstart.stop.prevent="handleChartTouch"
				@touchmove.stop.prevent="handleChartTouch"
				@click="handleChartClick"
			>
				<canvas 
					canvas-id="combinedChart" 
					id="combinedChart"
					class="main-chart-canvas"
					:style="{ width: canvasWidthPx + 'px', height: canvasHeightPx + 'px' }"
				></canvas>
			</view>
		</view>
		</view>


		<!-- 上下游水库（参考图1） -->
		<view class="updown-section" v-if="activeTab === 'updown'">
			<view class="simple-date-bar">
				<DateTimePicker 
					v-model="updownDate"
					@change="handleUpdownDateChange"
				/>
			</view>

			<view class="summary-cards three">
				<view class="summary-card">
					<text class="summary-value">{{ reservoirSummary.upstream_over_fsltdz }}/{{ reservoirSummary.upstream_count }}</text>
					<text class="summary-label">上游: 超汛限/总数</text>
				</view>
				<view class="summary-card">
					<text class="summary-value">{{ reservoirSummary.downstream_over_fsltdz }}/{{ reservoirSummary.downstream_count }}</text>
					<text class="summary-label">下游: 超汛限/总数</text>
				</view>
				<view class="summary-card">
					<text class="summary-value">-%</text>
					<text class="summary-label">蓄水率</text>
				</view>
			</view>

			<!-- 上游表格（仅当有数据时显示） -->
            <view class="table-section" v-if="upstreamReservoirs.length > 0">
                <view class="table-header">
                    <view class="th name">
                        <text>水库名称</text>
                        <text class="th-unit">(上游)</text>
                    </view>
                    <view class="th">
                        <text>库水位</text>
                        <text class="th-unit">(m)</text>
                    </view>
                    <view class="th">
                        <text>超汛限</text>
                        <text class="th-unit">(m)</text>
                    </view>
                    <view class="th">
                        <text>入流</text>
                        <text class="th-unit">(m³/s)</text>
                    </view>
                    <view class="th">
                        <text>出流</text>
                        <text class="th-unit">(m³/s)</text>
                    </view>
                </view>

				<view class="expand-bar" @click="isUpReservoirExpanded = !isUpReservoirExpanded">
					<text class="expand-text">站点无数据{{isUpReservoirExpanded ? '已展开' : '已折叠'}}</text>
					<text class="expand-action">{{ isUpReservoirExpanded ? '收起数据' : '展开数据' }}</text>
					<text class="expand-arrow">{{ isUpReservoirExpanded ? '⌃' : '⌄' }}</text>
				</view>

				<view class="table-row" v-for="item in upstreamReservoirsToShow" :key="item.name">
					<text class="td name">{{ item.name }}</text>
					<text class="td">{{ toDash(item.level) }}</text>
					<text class="td">{{ toDash(item.floodLimit) }}</text>
					<text class="td">{{ toDash(item.inflow) }}</text>
					<text class="td">{{ toDash(item.outflow) }}</text>
				</view>
			</view>

			<!-- 下游表格（仅当有数据时显示） -->
            <view class="table-section" v-if="downstreamReservoirs.length > 0">
                <view class="table-header">
                    <view class="th name">
                        <text>水库名称</text>
                        <text class="th-unit">(下游)</text>
                    </view>
                    <view class="th">
                        <text>库水位</text>
                        <text class="th-unit">(m)</text>
                    </view>
                    <view class="th">
                        <text>超汛限</text>
                        <text class="th-unit">(m)</text>
                    </view>
                    <view class="th">
                        <text>入流</text>
                        <text class="th-unit">(m³/s)</text>
                    </view>
                    <view class="th">
                        <text>出流</text>
                        <text class="th-unit">(m³/s)</text>
                    </view>
                </view>

				<view class="expand-bar" @click="isDownReservoirExpanded = !isDownReservoirExpanded">
					<text class="expand-text">站点无数据{{isDownReservoirExpanded ? '已展开' : '已折叠'}}</text>
					<text class="expand-action">{{ isDownReservoirExpanded ? '收起数据' : '展开数据' }}</text>
					<text class="expand-arrow">{{ isDownReservoirExpanded ? '⌃' : '⌄' }}</text>
				</view>

				<view class="table-row" v-for="item in downstreamReservoirsToShow" :key="item.name">
					<text class="td name">{{ item.name }}</text>
					<text class="td">{{ toDash(item.level) }}</text>
					<text class="td">{{ toDash(item.floodLimit) }}</text>
					<text class="td">{{ toDash(item.inflow) }}</text>
					<text class="td">{{ toDash(item.outflow) }}</text>
				</view>
			</view>
		</view>

		<!-- 河道断面（参考图2） -->
		<view class="river-section" v-if="activeTab === 'river'">
			<view class="simple-date-bar">
				<DateTimePicker 
					v-model="riverDate"
					@change="handleRiverDateChange"
				/>
			</view>

			<view class="summary-cards four">
				<view class="summary-card">
					<text class="summary-value">{{ riverSummary.upstream_over_grz }}/{{ riverSummary.upstream_count }}</text>
					<text class="summary-label">上游: 超保/总数</text>
				</view>
				<view class="summary-card">
					<text class="summary-value">{{ riverSummary.downstream_over_grz }}/{{ riverSummary.downstream_count }}</text>
					<text class="summary-label">下游: 超保/总数</text>
				</view>
				<view class="summary-card">
					<text class="summary-value">{{ riverSummary.upstream_over_wrz }}/{{ riverSummary.upstream_count }}</text>
					<text class="summary-label">上游: 超警/总数</text>
				</view>
				<view class="summary-card">
					<text class="summary-value">{{ riverSummary.downstream_over_wrz }}/{{ riverSummary.downstream_count }}</text>
					<text class="summary-label">下游: 超警/总数</text>
				</view>
			</view>

			<!-- 上游河道表（仅当有数据时显示） -->
			<view class="table-section" v-if="upstreamRiver.length > 0">
				<view class="table-header">
					<view class="th name">
						<text>河道名称</text>
						<text class="th-unit">(上游)</text>
					</view>
					<view class="th">
						<text>水位</text>
						<text class="th-unit">(m)</text>
					</view>
					<view class="th">
						<text>超警</text>
						<text class="th-unit">(m)</text>
					</view>
					<view class="th">
						<text>超保</text>
						<text class="th-unit">(m)</text>
					</view>
					<view class="th">
						<text>流量</text>
						<text class="th-unit">(m³/s)</text>
					</view>
				</view>

				<view class="expand-bar" @click="isUpRiverExpanded = !isUpRiverExpanded">
					<text class="expand-text">站点无数据{{isUpRiverExpanded ? '已展开' : '已折叠'}}</text>
					<text class="expand-action">{{ isUpRiverExpanded ? '收起数据' : '展开数据' }}</text>
					<text class="expand-arrow">{{ isUpRiverExpanded ? '⌃' : '⌄' }}</text>
				</view>

				<view class="table-row" v-for="item in upstreamRiverToShow" :key="item.name">
					<text class="td name">{{ item.name }}</text>
					<text class="td">{{ toDash(item.level) }}</text>
					<text class="td">{{ toDash(item.warnLevel) }}</text>
					<text class="td">{{ toDash(item.guaranteeLevel) }}</text>
					<text class="td">{{ toDash(item.flow) }}</text>
				</view>
			</view>

			<!-- 下游河道表（仅当有数据时显示） -->
			<view class="table-section" v-if="downstreamRiver.length > 0">
				<view class="table-header">
					<view class="th name">
						<text>河道名称</text>
						<text class="th-unit">(下游)</text>
					</view>
					<view class="th">
						<text>水位</text>
						<text class="th-unit">(m)</text>
					</view>
					<view class="th">
						<text>超警</text>
						<text class="th-unit">(m)</text>
					</view>
					<view class="th">
						<text>超保</text>
						<text class="th-unit">(m)</text>
					</view>
					<view class="th">
						<text>流量</text>
						<text class="th-unit">(m³/s)</text>
					</view>
				</view>

				<view class="expand-bar" @click="isDownRiverExpanded = !isDownRiverExpanded">
					<text class="expand-text">站点无数据{{isDownRiverExpanded ? '已展开' : '已折叠'}}</text>
					<text class="expand-action">{{ isDownRiverExpanded ? '收起数据' : '展开数据' }}</text>
					<text class="expand-arrow">{{ isDownRiverExpanded ? '⌃' : '⌄' }}</text>
				</view>

				<view class="table-row" v-for="item in downstreamRiverToShow" :key="item.name">
					<text class="td name">{{ item.name }}</text>
					<text class="td">{{ toDash(item.level) }}</text>
					<text class="td">{{ toDash(item.warnLevel) }}</text>
					<text class="td">{{ toDash(item.guaranteeLevel) }}</text>
					<text class="td">{{ toDash(item.flow) }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch, getCurrentInstance } from 'vue'
import { API_BASE_URL } from '@/config/api.js'
import DateTimePicker from './DateTimePicker.vue'
import LeafletMap from './LeafletMap.vue'
// #ifdef H5
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
// #endif

// 获取当前组件实例
const instance = getCurrentInstance()

// ==================== 常量配置 ====================
const CHART_COLORS = {
	RAIN: '#4FC3F7',
	INFLOW: '#1976D2',
	OUTFLOW: '#4CAF50',
	WATER_LEVEL: '#FF5722',
	NORMAL_LEVEL: '#FF9800',
	LIMIT_LEVEL: '#E53935',
}

// ==================== Props ====================
const props = defineProps({
	stationCode: {
		type: String,
		required: true
	}
})

// ==================== 响应式状态 ====================
// 标签切换
const activeTab = ref('chart')
const isQuerying = ref(false)

// 基础数据
const latestInfo = ref({})
const normalHighLevel = ref(null)
const rainfallData = ref([])
const flowData = ref([])
const waterStandards = ref({
	'normal_high_level': null,
	'flood_limit_level': null
})

// 上下游水库数据
const isUpReservoirExpanded = ref(false)
const isDownReservoirExpanded = ref(false)
const upstreamReservoirs = ref([])
const downstreamReservoirs = ref([])
const reservoirSummary = ref({
	total_stations: 0,
	upstream_count: 0,
	downstream_count: 0,
	upstream_over_fsltdz: 0,
	downstream_over_fsltdz: 0
})

// 河道断面数据
const isUpRiverExpanded = ref(false)
const isDownRiverExpanded = ref(false)
const upstreamRiver = ref([])
const downstreamRiver = ref([])
const riverSummary = ref({
	total_stations: 0,
	upstream_count: 0,
	downstream_count: 0,
	upstream_over_wrz: 0,
	upstream_over_grz: 0,
	downstream_over_wrz: 0,
	downstream_over_grz: 0
})

// 地图组件引用
const leafletMapRef = ref(null)
let map = null
let basinLayer = null
let outletLayer = null

// 地图数据
const basinGeometry = ref(null)
const outletPoint = ref(null)

// 画布尺寸
const canvasWidthPx = ref(320)
const canvasHeightPx = ref(280) // 调整为更紧凑的高度

// 使用 DateTimePicker 组件后，只需要简单的数据定义
// 主水库时间选择器
const mainStartDate = ref({ year: '', month: '', day: '', hour: '' })
const mainEndDate = ref({ year: '', month: '', day: '', hour: '' })

// 上下游水库时间选择器
const updownDate = ref({ year: '', month: '', day: '', hour: '' })

// 河道断面时间选择器
const riverDate = ref({ year: '', month: '', day: '', hour: '' })

// 主水库当前小时数据
const currentHourData = ref({
	rainfall: '--',
	inflow: '--',
	outflow: '--',
	waterLevel: '--'
})

// 主水库水情情势
const currentSituation = ref({
	sum_rain: '--',
	sum_inq: '--',
	outsum_otq: '--'
})

// 当前选中的小时时间
const currentHourTime = ref('10-28 10时')
const selectedChartIndex = ref(-1) // 选中的图表数据点索引

// ==================== 工具函数 ====================
const formatLabel = (tm) => (tm ? tm.slice(5, 16) : '')
const toNumberOrNull = (v) => (v == null ? null : Number(v))

// 格式化显示函数
const formatLevel = (v) => (v == null ? '--' : Number(v).toFixed(2))
const formatFlow = (v) => (v == null ? '--' : Number(v).toFixed(2))
const formatStorage = (v) => (v == null ? '--' : Number(v).toFixed(0))
const toDash = (v) => (v == null || v === '' ? '-' : Number(v).toFixed(2))

// 判断数据行是否有效
const hasReservoirData = (item) => {
	if (!item) return false
	return [item.level, item.floodLimit, item.inflow, item.outflow].some(
		v => v != null && Number.isFinite(Number(v))
	)
}

const hasRiverData = (item) => {
	if (!item) return false
	return [item.level, item.warnLevel, item.guaranteeLevel, item.flow].some(
		v => v != null && Number.isFinite(Number(v))
	)
}

// 初始化时间选择器数据
function initDateTimePickerData() {
	const now = new Date()
	const currentYear = now.getFullYear()
	
	// 生成年份数组（近5年）
	const years = []
	for (let i = currentYear - 4; i <= currentYear; i++) {
		years.push(i.toString())
	}
	
	// 生成月份数组
	const months = []
	for (let i = 1; i <= 12; i++) {
		months.push(i.toString().padStart(2, '0'))
	}
	
	// 生成小时数组
	const hours = []
	for (let i = 0; i < 24; i++) {
		hours.push(i.toString().padStart(2, '0'))
	}
	
	const yearIndex = years.indexOf(currentYear.toString())
	const monthIndex = now.getMonth() // 0-11
	const dayIndex = now.getDate() - 1 // 1-31 转为 0-30
	const hourIndex = now.getHours() // 0-23
	
	// 计算当前年月的实际天数
	const currentDaysInMonth = new Date(currentYear, now.getMonth() + 1, 0).getDate()
	const currentDays = []
	for (let i = 1; i <= currentDaysInMonth; i++) {
		currentDays.push(i.toString().padStart(2, '0'))
	}
	
	// 初始化上下游水库选择器（使用当前月份的实际天数）
	updownDateTimeRange.value = [years, months, currentDays, hours]
	updownDateTimeValue.value = [yearIndex, monthIndex, dayIndex, hourIndex]
	updownSelectedDate.value = {
		year: currentYear.toString(),
		month: months[monthIndex],
		day: currentDays[dayIndex],
		hour: hours[hourIndex]
	}
	
	// 初始化河道断面选择器（使用当前月份的实际天数）
	riverDateTimeRange.value = [years, months, currentDays, hours]
	riverDateTimeValue.value = [yearIndex, monthIndex, dayIndex, hourIndex]
	riverSelectedDate.value = {
		year: currentYear.toString(),
		month: months[monthIndex],
		day: currentDays[dayIndex],
		hour: hours[hourIndex]
	}
	
	// 初始化主水库选择器（开始时间为7天前，结束时间为当前）
	const lastWeekDate = new Date()
	lastWeekDate.setDate(lastWeekDate.getDate() - 7)
	const lastWeekYear = lastWeekDate.getFullYear()
	const lastWeekMonth = lastWeekDate.getMonth() + 1 // 1-12
	const lastWeekDay = lastWeekDate.getDate()
	
	// 计算开始时间的日期范围（根据7天前的年月）
	const startDaysInMonth = new Date(lastWeekYear, lastWeekMonth, 0).getDate()
	const startDays = []
	for (let i = 1; i <= startDaysInMonth; i++) {
		startDays.push(i.toString().padStart(2, '0'))
	}
	
	// 计算结束时间的日期范围（根据当前年月）
	const endDaysInMonth = new Date(currentYear, now.getMonth() + 1, 0).getDate()
	const endDays = []
	for (let i = 1; i <= endDaysInMonth; i++) {
		endDays.push(i.toString().padStart(2, '0'))
	}
	
	// 开始时间选择器
	mainDateTimeRange.value = [years, months, startDays, hours]
	const lastWeekYearIndex = years.indexOf(lastWeekYear.toString())
	const lastWeekMonthIndex = lastWeekMonth - 1 // 转为索引 0-11
	const lastWeekDayIndex = lastWeekDay - 1 // 转为索引
	
	mainDateTimeValue.value = [lastWeekYearIndex, lastWeekMonthIndex, lastWeekDayIndex, hourIndex]
	mainStartSelectedDate.value = {
		year: lastWeekYear.toString(),
		month: lastWeekMonth.toString().padStart(2, '0'),
		day: lastWeekDay.toString().padStart(2, '0'),
		hour: hours[hourIndex]
	}
	
	// 结束时间选择器
	mainEndDateTimeRange.value = [years, months, endDays, hours]
	mainEndDateTimeValue.value = [yearIndex, monthIndex, dayIndex, hourIndex]
	mainEndSelectedDate.value = {
		year: currentYear.toString(),
		month: months[monthIndex],
		day: endDays[dayIndex],
		hour: hours[hourIndex]
	}
}

// 根据年月更新日期数组
function updateDaysInMonth(year, month, type = 'updown') {
	const daysInMonth = new Date(parseInt(year), parseInt(month), 0).getDate()
	const days = []
	for (let i = 1; i <= daysInMonth; i++) {
		days.push(i.toString().padStart(2, '0'))
	}
	
	// 根据类型更新对应的日期范围和选中值
	switch (type) {
		case 'updown':
			updownDateTimeRange.value[2] = days
			if (updownDateTimeValue.value[2] >= days.length) {
				updownDateTimeValue.value[2] = days.length - 1
			}
			break
		case 'river':
			riverDateTimeRange.value[2] = days
			if (riverDateTimeValue.value[2] >= days.length) {
				riverDateTimeValue.value[2] = days.length - 1
			}
			break
		case 'mainStart':
			mainDateTimeRange.value[2] = days
			if (mainDateTimeValue.value[2] >= days.length) {
				mainDateTimeValue.value[2] = days.length - 1
			}
			break
		case 'mainEnd':
			mainEndDateTimeRange.value[2] = days
			if (mainEndDateTimeValue.value[2] >= days.length) {
				mainEndDateTimeValue.value[2] = days.length - 1
			}
			break
	}
}

// ==================== 地图 ====================
// 地图就绪回调
function handleMapReady(mapInstance) {
	// #ifdef H5
	console.log('[WaterDetail] 地图已就绪:', mapInstance)
	map = mapInstance
	
	// 添加流域边界和出水口图层
	addBasinLayer()
	addOutletLayer()
	// #endif
}

// 手动初始化地图（用于标签页切换时）
async function initChartMap() {
	// #ifdef H5
	if (leafletMapRef.value) {
		// 如果地图组件已存在，刷新地图尺寸
		if (map) {
			setTimeout(() => {
				leafletMapRef.value?.invalidateSize()
			}, 100)
		} else {
			// 如果地图还未初始化，手动初始化
			await leafletMapRef.value?.initMap()
		}
	}
	// #endif
}

// 添加流域边界图层
const addBasinLayer = () => {
	// #ifdef H5
	if (!map || !basinGeometry.value) return
	
	// 清除已有的流域边界图层
	if (basinLayer) {
		map.removeLayer(basinLayer)
		basinLayer = null
	}
	
	console.log('添加流域边界')
	basinLayer = L.geoJSON(basinGeometry.value, {
		style: {
			color: '#ff6600',
			weight: 3,
			fillOpacity: 0,
			opacity: 1
		}
	}).addTo(map)
	
	// 调整地图视野到流域边界
	map.fitBounds(basinLayer.getBounds())
	// #endif
}


// 添加出口点图层
const addOutletLayer = () => {
	// #ifdef H5
	if (!map || !outletPoint.value) return
	
	// 清除已有的出口点图层
	if (outletLayer) {
		map.removeLayer(outletLayer)
		outletLayer = null
	}
	
	const { lon, lat, name } = outletPoint.value
	
	// 创建红色圆点标记
	const outletMarker = L.circleMarker([lat, lon], {
		radius: 6,
		fillColor: '#ff0000',
		color: '#ff0000',
		weight: 2,
		opacity: 1,
		fillOpacity: 0.8
	})
	
	// 为出口点添加弹窗
	outletMarker.bindPopup(`
		<strong>流域出口</strong><br>
		名称: ${name}<br>
		坐标: ${lon}°, ${lat}°
	`)
	
	outletLayer = L.layerGroup([outletMarker]).addTo(map)
	// #endif
}

// ==================== 计算属性 ====================
// 顶部数据计算
const diffToNormal = computed(() => {
	if (normalHighLevel.value == null || latestInfo.value?.rz == null) return null
	return Number(latestInfo.value.rz) - Number(normalHighLevel.value)
})

const riseBadgeValue = computed(() => {
	if (diffToNormal.value == null) return '--'
	const sign = diffToNormal.value > 0 ? '+' : diffToNormal.value < 0 ? '-' : ''
	return `${sign}${Math.abs(diffToNormal.value).toFixed(2)}`
})

const statusText = computed(() => {
	if (diffToNormal.value == null) return '平'
	return diffToNormal.value < 0 ? '落' : '平'
})

const statusBadgeClass = computed(() => (statusText.value === '落' ? 'badge-fall' : 'badge-flat'))

// 上下游水库时间显示
const updownDateTimeLabel = computed(() => {
	const { year, month, day, hour } = updownSelectedDate.value
	if (!year || !month || !day || !hour) return '请选择时间'
	return `${year}/${month}/${day} ${hour}时`
})

// 河道断面时间显示
const riverDateTimeLabel = computed(() => {
	const { year, month, day, hour } = riverSelectedDate.value
	if (!year || !month || !day || !hour) return '请选择时间'
	return `${year}/${month}/${day} ${hour}时`
})

// 主水库开始时间显示
const mainStartDateTimeLabel = computed(() => {
	const { year, month, day, hour } = mainStartSelectedDate.value
	if (!year || !month || !day || !hour) return '请选择时间'
	return `${year}/${month}/${day} ${hour}时`
})

// 主水库结束时间显示
const mainEndDateTimeLabel = computed(() => {
	const { year, month, day, hour } = mainEndSelectedDate.value
	if (!year || !month || !day || !hour) return '请选择时间'
	return `${year}/${month}/${day} ${hour}时`
})

// 列表展示（收起时过滤无数据行）
const upstreamReservoirsToShow = computed(() => {
	const list = upstreamReservoirs.value
	return isUpReservoirExpanded.value ? list : list.filter(hasReservoirData)
})

const downstreamReservoirsToShow = computed(() => {
	const list = downstreamReservoirs.value
	return isDownReservoirExpanded.value ? list : list.filter(hasReservoirData)
})

const upstreamRiverToShow = computed(() => {
	const list = upstreamRiver.value
	return isUpRiverExpanded.value ? list : list.filter(hasRiverData)
})

const downstreamRiverToShow = computed(() => {
	const list = downstreamRiver.value
	return isDownRiverExpanded.value ? list : list.filter(hasRiverData)
})

// ==================== API 调用 ====================
// 获取流域详情
async function fetchBasinGeometry() {
	try {
		const response = await uni.request({
			url: `${API_BASE_URL}/api/get_reservoir_by_stcd?basin=${props.stationCode}`,
			method: 'GET'
		})
		if (response.data.success) {
			// 设置地图相关数据
			basinGeometry.value = response.data.data.geometry_geojson || null
			outletPoint.value = {
				lon: response.data.data.outlet_coordinates.longitude,
				lat: response.data.data.outlet_coordinates.latitude,
				name: response.data.data.stnm
			}
			// 流域面数据到达后尝试叠加图层
			addBasinLayer()
			addOutletLayer()
			// 刷新地图尺寸以确保可见
			setTimeout(() => { map && map.invalidateSize() }, 100)
		}
	} catch (e) {
		console.error('获取流域面失败:', e)
	}
}

// 获取最新信息
async function fetchLatestInfo() {
	try {
		const startTime = Date.now()
		console.log('[fetchLatestInfo] 开始获取最新信息')
		// 获取今天8点作为结束时间
		const today = new Date()
		const year = today.getFullYear()
		const month = String(today.getMonth() + 1).padStart(2, '0')
		const day = String(today.getDate()).padStart(2, '0')
		const endTimeStr = `${year}-${month}-${day} 08:00:00`
		console.log('最新数据时间：' + `${endTimeStr}`)
		
		const url = `${API_BASE_URL}/api/get_rsvr_latest_info?stcd=${props.stationCode}&end_time_str=${encodeURIComponent(endTimeStr)}&days=7`
		const res = await uni.request({ url, method: 'GET', timeout: 10000 }) // 设置10秒超时 

		const elapsed = Date.now() - startTime
		console.warn(`[fetchLatestInfo] 接口响应耗时: ${elapsed}ms`)
		
		if (res?.data?.success) {
			const payload = res.data.data || {}
			latestInfo.value = payload.latest_data || {}
			normalHighLevel.value = payload.water_standards?.normal_high_level ?? null
		} else {
			console.error('最新信息接口错误:', res?.data)
		}
	} catch (err) {
		console.error('最新信息接口异常:', err)
	}
}

// 获取逐小时水情数据
async function fetchWaterData() {
	try {
		// 使用 DateTimePicker 组件的数据
		const { year: startYear, month: startMonth, day: startDay, hour: startHour } = mainStartDate.value
		const { year: endYear, month: endMonth, day: endDay, hour: endHour } = mainEndDate.value
		
		const startTimeStr = `${startYear}-${startMonth}-${startDay} ${startHour}:00:00`
		const endTimeStr = `${endYear}-${endMonth}-${endDay} ${endHour}:00:00`
		const url = `${API_BASE_URL}/api/get_rsvr_hour_data?stcd=${props.stationCode}&start_time_str=${encodeURIComponent(startTimeStr)}&end_time_str=${encodeURIComponent(endTimeStr)}`
		
		const res = await uni.request({ url, method: 'GET' })
		console.log('逐小时接口响应:', res)

		if (res?.data?.success) {
			const payload = res.data.data || {}
			const list = Array.isArray(payload.data) ? payload.data : []

			// 获取逐小时水情数据——正常高水位、汛限水位
			if (payload.water_standards?.normal_high_level != null) {
				waterStandards.value.normal_high_level = Number(payload.water_standards.normal_high_level)
			}
			if (payload.water_standards?.flood_limit_level != null) {
				waterStandards.value.flood_limit_level = Number(payload.water_standards.flood_limit_level)
			}

			// 转换图表数据
			rainfallData.value = list.map(item => ({
				time: formatLabel(item.tm),
				value: Number(item.rain ?? 0)
			}))

			flowData.value = list.map(item => ({
				time: formatLabel(item.tm),
				inflow: toNumberOrNull(item.inq),
				outflow: toNumberOrNull(item.otq),
				waterLevel: toNumberOrNull(item.rz)
			}))

		console.log('转换后的降雨数据:', rainfallData.value)
		console.log('转换后的流量水位数据:', flowData.value)

		// 从 summary 中获取累计值并更新水情情势
		if (payload.summary) {
			const summary = payload.summary
			currentSituation.value = {
				sum_rain: summary.sum_rain != null ? Number(summary.sum_rain).toFixed(1) : '--',
				sum_inq: summary.sum_inq != null ? Number(summary.sum_inq).toFixed(2) : '--',
				sum_otq: summary.sum_otq != null ? Number(summary.sum_otq).toFixed(2) : '--'
			}
			console.log('更新水情情势（来自summary）:', currentSituation.value)
		}

		// 数据获取成功后初始化显示并绘制图表
		nextTick(() => {
			initializeCurrentHourData()
			// 初始化数据后再绘制图表，这样指示线会显示
			nextTick(() => {
				drawCombinedChart()
			})
		})
		} else {
			console.error('逐小时接口失败:', res?.data)
			resetChartData()
		}
	} catch (error) {
		console.error('获取水情数据失败:', error)
		resetChartData()
	}
}

// 获取上下游水库/河道数据
async function fetchStreamDataAtTime(type = 'rsvr') {
	try {
		// 使用 DateTimePicker 组件的数据
		let endTimeStr
		if (type === 'rsvr') {
			const { year, month, day, hour } = updownDate.value
			endTimeStr = `${year}-${month}-${day} ${hour}:00:00`
		} else {
			const { year, month, day, hour } = riverDate.value
			endTimeStr = `${year}-${month}-${day} ${hour}:00:00`
		}
		
		const url = `${API_BASE_URL}/api/get_stream_data_at_time?basin=${props.stationCode}&end_time_str=${encodeURIComponent(endTimeStr)}&type=${type}`
		
		const res = await uni.request({ url, method: 'GET' })
		
		if (res?.data?.success) {
			const payload = res.data.data || {}
			const upListRaw = Array.isArray(payload.upstream) ? payload.upstream : []
			const downListRaw = Array.isArray(payload.downstream) ? payload.downstream : []

			if (type === 'rsvr') {
				updateReservoirData(upListRaw, downListRaw, payload)
			} else if (type === 'river') {
				updateRiverData(upListRaw, downListRaw, payload)
			}
		} else {
			console.error('上下游/河道接口失败:', res?.data)
			resetStreamData(type)
		}
	} catch (error) {
		console.error('获取上下游/河道数据失败:', error)
		resetStreamData(type)
	}
}

// ==================== 数据更新辅助函数 ====================
function updateReservoirData(upListRaw, downListRaw, payload) {
	// 更新统计数据
	if (payload?.summary) {
		reservoirSummary.value = {
			total_stations: payload.summary.total_stations || 0,
			upstream_count: payload.summary.upstream_count || 0,
			downstream_count: payload.summary.downstream_count || 0,
			upstream_over_fsltdz: payload.summary.upstream_over_fsltdz || 0,
			downstream_over_fsltdz: payload.summary.downstream_over_fsltdz || 0
		}
	}

	const mapReservoir = (item) => ({
		name: item?.stnm ?? '',
		level: toNumberOrNull(item?.rz),
		floodLimit: toNumberOrNull(item?.fsltdz_diff),
		inflow: toNumberOrNull(item?.inq),
		outflow: toNumberOrNull(item?.otq)
	})

	upstreamReservoirs.value = upListRaw.map(mapReservoir)
	downstreamReservoirs.value = downListRaw.map(mapReservoir)
}

function updateRiverData(upListRaw, downListRaw, payload) {
	// 更新统计数据
	if (payload?.summary) {
		riverSummary.value = {
			total_stations: payload.summary.total_stations || 0,
			upstream_count: payload.summary.upstream_count || 0,
			downstream_count: payload.summary.downstream_count || 0,
			upstream_over_wrz: payload.summary.upstream_over_wrz || 0,
			upstream_over_grz: payload.summary.upstream_over_grz || 0,
			downstream_over_wrz: payload.summary.downstream_over_wrz || 0,
			downstream_over_grz: payload.summary.downstream_over_grz || 0
		}
	}

	const mapRiver = (item) => ({
		name: item?.stnm ?? '',
		level: toNumberOrNull(item?.z),
		warnLevel: toNumberOrNull(item?.wrz_diff),
		guaranteeLevel: toNumberOrNull(item?.grz_diff),
		flow: toNumberOrNull(item?.q)
	})

	upstreamRiver.value = upListRaw.map(mapRiver)
	downstreamRiver.value = downListRaw.map(mapRiver)
}

function resetChartData() {
	rainfallData.value = []
	flowData.value = []
}

function resetStreamData(type) {
	if (type === 'rsvr') {
		upstreamReservoirs.value = []
		downstreamReservoirs.value = []
		reservoirSummary.value = {
			total_stations: 0,
			upstream_count: 0,
			downstream_count: 0,
			upstream_over_fsltdz: 0,
			downstream_over_fsltdz: 0
		}
	} else {
		upstreamRiver.value = []
		downstreamRiver.value = []
		riverSummary.value = {
			total_stations: 0,
			upstream_count: 0,
			downstream_count: 0,
			upstream_over_wrz: 0,
			upstream_over_grz: 0,
			downstream_over_wrz: 0,
			downstream_over_grz: 0
		}
	}
}

// ==================== 事件处理 ====================
// 上下游水库时间选择器变更
// ==================== 使用 DateTimePicker 组件后的简化事件处理 ====================

// 主水库时间变更
function handleMainDateChange() {
	console.log('主水库时间变更:', mainStartDate.value, mainEndDate.value)
	handleQueryButtonClick()
}

// 上下游水库时间变更
function handleUpdownDateChange() {
	console.log('上下游水库时间变更:', updownDate.value)
	fetchStreamDataAtTime('rsvr')
}

// 河道断面时间变更
function handleRiverDateChange() {
	console.log('河道断面时间变更:', riverDate.value)
	fetchStreamDataAtTime('river')
}

// 处理图表交互（触摸/点击）
const handleChartInteraction = (pageX) => {
	if (!flowData.value || flowData.value.length === 0) return
	
	// 查询容器位置
	uni.createSelectorQuery()
		.select('.chart-canvas-wrapper')
		.boundingClientRect()
		.exec((res) => {
			if (!res || !res[0]) {
				console.log('无法获取容器位置')
				return
			}
			
			const rect = res[0]
			const canvasWidth = canvasWidthPx.value
			// 使用与绘图相同的 padding 值
			const paddingLeft = 25
			const paddingRight = 50
			const chartWidth = canvasWidth - paddingLeft - paddingRight
			
			// 计算相对于容器的坐标
			const containerX = pageX - rect.left
			// 再减去左边距得到相对于图表区域的坐标
			const relativeX = containerX - paddingLeft
			
			// 计算对应的数据点索引
			const n = flowData.value.length
			const xStep = n > 1 ? chartWidth / (n - 1) : chartWidth / 2
			let index = Math.round(relativeX / xStep)
			
			// 限制在有效范围
			index = Math.max(0, Math.min(n - 1, index))
			
			selectedChartIndex.value = index
			updateDataDisplay(index)
			drawCombinedChart()
		})
}

// 图表触摸事件（支持滑动）
const handleChartTouch = (e) => {
	const touch = e.touches?.[0] || e.changedTouches?.[0]
	if (!touch) return
	
	// 获取触摸坐标（使用 pageX 相对于页面）
	const touchX = touch.pageX || touch.clientX || touch.x || 0
	handleChartInteraction(touchX)
}

// 图表点击事件
const handleChartClick = (e) => {
	// 获取点击坐标（使用 detail.x 相对于页面）
	const clickX = e.detail?.x || e.pageX || e.x || 0
	handleChartInteraction(clickX)
}

// 提取数据显示更新逻辑
function updateDataDisplay(index) {
	if (index < 0 || index >= flowData.value.length) return
	
	const dataPoint = flowData.value[index]
	
	// 更新当前小时数据
	currentHourData.value = {
		rainfall: rainfallData.value[index]?.value?.toFixed(1) || '--',
		inflow: dataPoint.inflow !== null && Number.isFinite(dataPoint.inflow) 
			? dataPoint.inflow.toFixed(2) 
			: '--',
		outflow: dataPoint.outflow !== null && Number.isFinite(dataPoint.outflow) 
			? dataPoint.outflow.toFixed(2) 
			: '--',
		waterLevel: dataPoint.waterLevel !== null && Number.isFinite(dataPoint.waterLevel) 
			? dataPoint.waterLevel.toFixed(2) 
			: '--'
	}
	
	// 更新时间显示
	currentHourTime.value = dataPoint.time || '--'
	
	// 注意：水情情势（累计值）保持不变，始终显示接口返回的 summary 数据
	// 不根据点击位置动态计算累计值
}

async function handleQueryButtonClick() {
	if (isQuerying.value) return

	try {
		isQuerying.value = true
		const { year: startYear, month: startMonth, day: startDay, hour: startHour } = mainStartDate.value
		const { year: endYear, month: endMonth, day: endDay, hour: endHour } = mainEndDate.value
		
		console.log('查询水情数据:', {
			stationCode: props.stationCode,
			startTime: `${startYear}-${startMonth}-${startDay} ${startHour}:00`,
			endTime: `${endYear}-${endMonth}-${endDay} ${endHour}:00`
		})

		// 并发拉取所有数据（fetchWaterData 会自动绘制图表并初始化数据显示）
		await Promise.all([
			fetchWaterData(),
		])
	} catch (error) {
		console.error('查询水情数据失败:', error)
	} finally {
		isQuerying.value = false
	}
}

// 初始化当前小时数据（显示最后一个数据点）
const initializeCurrentHourData = () => {
	if (!flowData.value || flowData.value.length === 0) return
	
	const lastIndex = flowData.value.length - 1
	selectedChartIndex.value = lastIndex
	const dataPoint = flowData.value[lastIndex]
	
	// 更新当前小时数据
	currentHourData.value = {
		rainfall: rainfallData.value[lastIndex]?.value?.toFixed(1) || '--',
		inflow: dataPoint.inflow !== null && Number.isFinite(dataPoint.inflow) 
			? dataPoint.inflow.toFixed(2) 
			: '--',
		outflow: dataPoint.outflow !== null && Number.isFinite(dataPoint.outflow) 
			? dataPoint.outflow.toFixed(2) 
			: '--',
		waterLevel: dataPoint.waterLevel !== null && Number.isFinite(dataPoint.waterLevel) 
			? dataPoint.waterLevel.toFixed(2) 
			: '--'
	}
	
	// 更新时间显示
	currentHourTime.value = dataPoint.time || '--'
	
	// 注意：水情情势（累计值）现在从 fetchWaterData 的 summary 中获取，不在这里计算
}

// ==================== 图表绘制 ====================
function initCanvasSize() {
	const { windowWidth } = uni.getSystemInfoSync()
	const w = Math.max(windowWidth || 320, 320)
	// 宽度接近100%，减去容器padding
	canvasWidthPx.value = Math.round(w * 0.98)
	// 增加高度以容纳更多内容：从280rpx增加到480rpx
	canvasHeightPx.value = Math.round((480 / 750) * w)
}

function drawCombinedChart() {
	const ctx = uni.createCanvasContext('combinedChart')
	const { windowWidth } = uni.getSystemInfoSync()
	const fallbackWidth = Math.max(windowWidth || 320, 320)
	const fallbackHeight = Math.round((480 / 750) * fallbackWidth)

	const canvasWidth = canvasWidthPx.value || fallbackWidth
	const canvasHeight = canvasHeightPx.value || fallbackHeight
	
	// 优化布局：减小边距让图表更充满
	const padding = { top: 20, right: 50, bottom: 30, left: 25 }
	const chartWidth = canvasWidth - padding.left - padding.right

	// 区域划分 - 降雨和流量水位图表
	const gapBetweenCharts = 25 // 两个图表之间的间距
	const availableHeight = canvasHeight - padding.top - padding.bottom - gapBetweenCharts
	const chartHeight = availableHeight / 2 // 两个图表平分可用高度
	
	const rainfallHeight = chartHeight
	const rainfallTop = padding.top
	const rainfallBottom = rainfallTop + rainfallHeight
	
	const flowHeight = chartHeight
	const flowTop = rainfallBottom + gapBetweenCharts

	ctx.clearRect(0, 0, canvasWidth, canvasHeight)

	// 绘制降雨柱状图
	const xStep = drawRainfallChart(ctx, padding, chartWidth, rainfallTop, rainfallHeight)

	// 绘制流量水位图
	drawFlowChart(ctx, padding, chartWidth, canvasWidth, flowTop, flowHeight, rainfallTop, rainfallHeight, xStep)

	// 绘制触摸指示线（如果有选中的数据点）
	console.warn("绘制触摸指示线索引：" + selectedChartIndex.value)
	if (selectedChartIndex.value >= 0 && xStep) {
		drawTouchIndicator(ctx, padding, rainfallTop, flowTop, flowHeight, xStep, selectedChartIndex.value)
	}

	ctx.draw()
}

function drawRainfallChart(ctx, padding, chartWidth, rainfallTop, rainfallHeight) {
	const rainfallValues = rainfallData.value.map(d => Number(d.value || 0))
	const maxRainfall = Math.max(...rainfallValues, 15) // 至少15mm刻度
	const rainfallMax = Math.ceil(maxRainfall / 5) * 5 // 向上取整到5的倍数
	
	// 根据数据量动态调整柱子宽度
	const dataCount = rainfallData.value.length || 1
	const n = Math.max(dataCount, 2)
	const xStep = n > 1 ? chartWidth / (n - 1) : chartWidth / 2
	
	let barWidthRatio = 0.6 // 默认柱子占60%
	if (dataCount > 100) {
		barWidthRatio = 0.8 // 数据多时占80%
	} else if (dataCount > 50) {
		barWidthRatio = 0.7
	}
	const barWidth = xStep * barWidthRatio

	// 绘制降雨标题
	ctx.setFillStyle('#00BCD4')
	ctx.setFontSize(12)
	ctx.setTextAlign('left')
	ctx.fillText('降雨(mm)', padding.left, rainfallTop - 8)

	// 绘制降雨区域边框（与流量图对齐）
	ctx.setStrokeStyle('#E0E0E0')
	ctx.setLineWidth(1)
	// 左边框
	ctx.beginPath()
	ctx.moveTo(padding.left, rainfallTop)
	ctx.lineTo(padding.left, rainfallTop + rainfallHeight)
	ctx.stroke()
	// 右边框
	ctx.beginPath()
	ctx.moveTo(chartWidth + padding.left, rainfallTop)
	ctx.lineTo(chartWidth + padding.left, rainfallTop + rainfallHeight)
	ctx.stroke()
	// 底边框
	ctx.beginPath()
	ctx.moveTo(padding.left, rainfallTop + rainfallHeight)
	ctx.lineTo(chartWidth + padding.left, rainfallTop + rainfallHeight)
	ctx.stroke()

	// 绘制降雨刻度（左侧，从上到下：0 -> 最大值）
	ctx.setFillStyle('#666')
	ctx.setFontSize(9)
	ctx.setTextAlign('right')
	for (let i = 0; i <= 3; i++) {
		const value = (rainfallMax / 3) * i // 从0开始递增
		const y = rainfallTop + (rainfallHeight / 3) * i
		ctx.fillText(value.toFixed(0), padding.left - 5, y + 3)
		
		// 绘制刻度线
		ctx.setStrokeStyle('#E0E0E0')
		ctx.setLineWidth(0.5)
		ctx.beginPath()
		ctx.moveTo(padding.left - 5, y)
		ctx.lineTo(padding.left, y)
		ctx.stroke()
	}

	// 绘制竖向网格线（与流量图对齐）
	ctx.setStrokeStyle('#E8F5E9')
	ctx.setLineWidth(1)
	for (let i = 0; i < dataCount; i++) {
		const x = padding.left + xStep * i
		ctx.beginPath()
		ctx.moveTo(x, rainfallTop)
		ctx.lineTo(x, rainfallTop + rainfallHeight)
		ctx.stroke()
	}

	// 绘制降雨柱子（从底部向上）
	// 使用与流量水位图相同的 x 坐标计算方式，确保对齐
	rainfallData.value.forEach((item, index) => {
		const x = padding.left + xStep * index
		const barHeight = (Number(item.value || 0) / rainfallMax) * rainfallHeight
		if (item.value > 0) {
			ctx.setFillStyle(CHART_COLORS.RAIN)
			// 从顶部向下绘制，柱子居中对齐数据点
			ctx.fillRect(x - barWidth / 2, rainfallTop, barWidth, barHeight)
		}
	})
	
	return xStep
}

function drawFlowChart(ctx, padding, chartWidth, canvasWidth, flowTop, flowHeight, rainfallTop, rainfallHeight, xStep) {
	// 绘制网格
	drawGrid(ctx, padding, canvasWidth, flowTop, flowHeight)

	// 计算刻度范围
	const { fMin, fMax, wlMin, wlMax } = calculateScales()

	// 绘制刻度
	drawScales(ctx, padding, canvasWidth, flowTop, flowHeight, fMin, fMax, wlMin, wlMax)

	// 绘制正常高水位线
	drawNormalWaterLine(ctx, padding, canvasWidth, flowTop, flowHeight, wlMin, wlMax)

	// 绘制时间轴（使用传入的xStep）
	drawTimeAxis(ctx, padding, chartWidth, canvasWidth, flowTop, flowHeight, xStep)

	// 绘制折线
	drawFlowLines(ctx, padding, flowTop, flowHeight, xStep, fMin, fMax, wlMin, wlMax)
	
	// 绘制图例
	// drawLegend(ctx, padding, canvasWidth, flowTop)
}

function drawGrid(ctx, padding, canvasWidth, flowTop, flowHeight) {
	// 绘制横向网格线
	ctx.setStrokeStyle('#E8F5E9')
	ctx.setLineWidth(1)
	for (let i = 0; i <= 5; i++) {
		const y = flowTop + (flowHeight / 5) * i
		ctx.beginPath()
		ctx.moveTo(padding.left, y)
		ctx.lineTo(canvasWidth - padding.right, y)
		ctx.stroke()
	}
	
	// 绘制左右边框
	ctx.setStrokeStyle('#E0E0E0')
	ctx.setLineWidth(1)
	ctx.beginPath()
	ctx.moveTo(padding.left, flowTop)
	ctx.lineTo(padding.left, flowTop + flowHeight)
	ctx.stroke()
	
	ctx.beginPath()
	ctx.moveTo(canvasWidth - padding.right, flowTop)
	ctx.lineTo(canvasWidth - padding.right, flowTop + flowHeight)
	ctx.stroke()
}

function calculateScales() {
	const inflowVals = flowData.value.map(d => d.inflow).filter(v => Number.isFinite(v))
	const outflowVals = flowData.value.map(d => d.outflow).filter(v => Number.isFinite(v))
	const wlVals = flowData.value.map(d => d.waterLevel).filter(v => Number.isFinite(v))
	const normalWL = waterStandards.value?.normal_high_level
	const floodWL = waterStandards.value?.flood_limit_level
	let wlAll = wlVals.slice()
	if (Number.isFinite(normalWL)) wlAll.push(normalWL)
	if (Number.isFinite(floodWL)) wlAll.push(floodWL)
	const flowValsAll = [...inflowVals, ...outflowVals]

	let flowMin = flowValsAll.length ? Math.min(...flowValsAll) : 0
	let flowMax = flowValsAll.length ? Math.max(...flowValsAll) : 1
	if (flowMax === flowMin) {
		const pad = Math.max(Math.abs(flowMax) * 0.1, 1)
		flowMin -= pad
		flowMax += pad
	}

	let waterLevelMin = wlAll.length ? Math.min(...wlAll) : 0
	let waterLevelMax = wlAll.length ? Math.max(...wlAll) : 1
	if (waterLevelMax === waterLevelMin) {
		const pad = Math.max(Math.abs(waterLevelMax) * 0.0015, 0.1)
		waterLevelMin -= pad
		waterLevelMax += pad
	}

	const flowPad = (flowMax - flowMin) * 0.1
	const wlPad = (waterLevelMax - waterLevelMin) * 0.1

	return {
		fMin: flowMin - flowPad,
		fMax: flowMax + flowPad,
		wlMin: waterLevelMin - wlPad,
		wlMax: waterLevelMax + wlPad
	}
}

function drawScales(ctx, padding, canvasWidth, flowTop, flowHeight, fMin, fMax, wlMin, wlMax) {
	const flowTickDigits = (fMax - fMin) < 1 ? 2 : (fMax - fMin) < 10 ? 1 : 0
	
	// 左侧流量标题 - 入库（蓝色）
	ctx.setFillStyle(CHART_COLORS.INFLOW)
	ctx.setFontSize(12)
	ctx.setTextAlign('left')
	ctx.fillText('入库', padding.left, flowTop - 8)
	
	// 斜杠（灰色）
	ctx.setFillStyle('#666')
	const inflowTextWidth = ctx.measureText('入库').width || 20
	ctx.fillText('/', padding.left + inflowTextWidth, flowTop - 8)
	
	// 左侧流量标题 - 出库（绿色）
	ctx.setFillStyle(CHART_COLORS.OUTFLOW)
	const slashWidth = ctx.measureText('/').width || 6
	ctx.fillText('出库', padding.left + inflowTextWidth + slashWidth, flowTop - 8)
	
	// 单位（灰色）
	ctx.setFillStyle('#666')
	const outflowTextWidth = ctx.measureText('出库').width || 24
	ctx.fillText('(m³/s)', padding.left + inflowTextWidth + slashWidth + outflowTextWidth, flowTop - 8)
	
	// 左侧流量刻度
	ctx.setFillStyle('#666')
	ctx.setFontSize(9)
	ctx.setTextAlign('right')
	for (let i = 0; i <= 5; i++) {
		const value = fMin + (fMax - fMin) * (5 - i) / 5
		const y = flowTop + (flowHeight / 5) * i
		ctx.fillText(value.toFixed(flowTickDigits), padding.left - 1, y + 3)
	}

	// 右侧水位标题
	ctx.setFillStyle(CHART_COLORS.WATER_LEVEL)
	ctx.setFontSize(12)
	ctx.setTextAlign('right')
	ctx.fillText('水位(m)', canvasWidth - padding.right, flowTop - 8)
	
	// 右侧水位刻度
	ctx.setFillStyle('#666')
	ctx.setFontSize(9)
	ctx.setTextAlign('left')
	for (let i = 0; i <= 5; i++) {
		const value = wlMin + (wlMax - wlMin) * (5 - i) / 5
		const y = flowTop + (flowHeight / 5) * i
		ctx.fillText(value.toFixed(flowTickDigits), canvasWidth - padding.right + 5, y + 3)
	}
}

function drawNormalWaterLine(ctx, padding, canvasWidth, flowTop, flowHeight, wlMin, wlMax) {
	const normalWaterLevel = waterStandards.value?.normal_high_level
	const floodLimitLevel = waterStandards.value?.flood_limit_level
	
	const drawLine = (level, strokeColor, bgColor, labelText) => {
		if (!Number.isFinite(level)) return
		if (level < wlMin || level > wlMax) return
		const y = flowTop + flowHeight - ((level - wlMin) / (wlMax - wlMin)) * flowHeight
		ctx.setStrokeStyle(strokeColor)
		ctx.setLineWidth(1.5)
		ctx.setLineDash([5, 5])
		ctx.beginPath()
		ctx.moveTo(padding.left, y)
		ctx.lineTo(canvasWidth - padding.right, y)
		ctx.stroke()
		ctx.setLineDash([])
		const labelX = canvasWidth - padding.right - 80
		const labelY = y - 8
		ctx.setFillStyle(bgColor)
		ctx.fillRect(labelX - 5, labelY - 12, 85, 20)
		ctx.setFillStyle(strokeColor)
		ctx.setFontSize(12)
		ctx.setTextAlign('left')
		ctx.fillText(labelText, labelX, labelY)
	}
	
	drawLine(normalWaterLevel, CHART_COLORS.NORMAL_LEVEL, 'rgba(255, 152, 0, 0.1)', '正常高水位')
	drawLine(floodLimitLevel, CHART_COLORS.LIMIT_LEVEL, 'rgba(229, 57, 53, 0.1)', '汛限水位')
}

function drawTimeAxis(ctx, padding, chartWidth, canvasWidth, flowTop, flowHeight, xStep) {
	const labelsBase = flowData.value.length ? flowData.value.map(d => d.time) : rainfallData.value.map(d => d.time)
	const n = Math.max(labelsBase.length, 2)

	// 底部横线
	ctx.setStrokeStyle('#999')
	ctx.setLineWidth(1)
	ctx.beginPath()
	ctx.moveTo(padding.left, flowTop + flowHeight)
	ctx.lineTo(canvasWidth - padding.right, flowTop + flowHeight)
	ctx.stroke()

	// 根据数据量智能调整时间标签显示密度 - 更激进的策略避免重叠
	let tickEvery = 1
	if (n > 168) {
		// 超过7天（168小时），每48小时显示一个
		tickEvery = Math.ceil(n / 4)
	} else if (n > 72) {
		// 3-7天，每24小时显示一个
		tickEvery = Math.ceil(n / 6)
	} else if (n > 48) {
		// 2-3天，每12小时显示一个
		tickEvery = Math.ceil(n / 6)
	} else if (n > 24) {
		// 1-2天，每6小时显示一个
		tickEvery = Math.ceil(n / 5)
	} else if (n > 12) {
		// 半天到1天，每3小时显示一个
		tickEvery = 3
	} else {
		// 半天以内，每2小时显示一个
		tickEvery = 2
	}
	
	ctx.setFillStyle('#666')
	ctx.setFontSize(9)
	ctx.setTextAlign('left')
	
	for (let i = 0; i < n; i += tickEvery) {
		const x = padding.left + xStep * i
		
		// 绘制竖向刻度线
		ctx.setStrokeStyle('#E0E0E0')
		ctx.setLineWidth(0.5)
		ctx.beginPath()
		ctx.moveTo(x, flowTop)
		ctx.lineTo(x, flowTop + flowHeight)
		ctx.stroke()
		
		// 绘制底部刻度标记
		ctx.setStrokeStyle('#999')
		ctx.setLineWidth(1)
		ctx.beginPath()
		ctx.moveTo(x, flowTop + flowHeight)
		ctx.lineTo(x, flowTop + flowHeight + 5)
		ctx.stroke()
		
		// 绘制时间标签（两行：日期和时间）
		const timeText = labelsBase[i] || ''
		if (timeText) {
			// 解析时间格式 MM-DD HH:mm
			const parts = timeText.split(' ')
			if (parts.length === 2) {
				ctx.fillText(parts[0], x, flowTop + flowHeight + 15) // 日期
				ctx.fillText(parts[1], x, flowTop + flowHeight + 28) // 时间
			} else {
				ctx.fillText(timeText, x, flowTop + flowHeight + 15)
			}
		}
	}
	
	// 确保显示最后一个时间点
	if ((n - 1) % tickEvery !== 0) {
		const lastIndex = n - 1
		const x = padding.left + xStep * lastIndex
		
		ctx.setStrokeStyle('#E0E0E0')
		ctx.setLineWidth(0.5)
		ctx.beginPath()
		ctx.moveTo(x, flowTop)
		ctx.lineTo(x, flowTop + flowHeight)
		ctx.stroke()
		
		ctx.setStrokeStyle('#999')
		ctx.setLineWidth(1)
		ctx.beginPath()
		ctx.moveTo(x, flowTop + flowHeight)
		ctx.lineTo(x, flowTop + flowHeight + 5)
		ctx.stroke()
		
		const timeText = labelsBase[lastIndex] || ''
		if (timeText) {
			const parts = timeText.split(' ')
			if (parts.length === 2) {
				ctx.fillText(parts[0], x, flowTop + flowHeight + 15)
				ctx.fillText(parts[1], x, flowTop + flowHeight + 28)
			} else {
				ctx.fillText(timeText, x, flowTop + flowHeight + 15)
			}
		}
	}

	return xStep
}

function drawFlowLines(ctx, padding, flowTop, flowHeight, xStep, fMin, fMax, wlMin, wlMax) {
	const inflowArr = flowData.value.map(d => d.inflow)
	const outflowArr = flowData.value.map(d => d.outflow)
	const wlArr = flowData.value.map(d => d.waterLevel)
	
	// 限制 y 值在绘制区域内，避免超出边界
	const flowToY = (val) => {
		const y = flowTop + flowHeight - ((val - fMin) / (fMax - fMin)) * flowHeight
		return Math.max(flowTop, Math.min(flowTop + flowHeight, y))
	}
	const wlToY = (val) => {
		const y = flowTop + flowHeight - ((val - wlMin) / (wlMax - wlMin)) * flowHeight
		return Math.max(flowTop, Math.min(flowTop + flowHeight, y))
	}

	// 1. 先绘制水位填充区域（最底层）
	const validWlPoints = []
	wlArr.forEach((val, index) => {
		if (Number.isFinite(val)) {
			const x = padding.left + xStep * index
			const y = wlToY(val)
			validWlPoints.push({ x, y })
		}
	})
	
	if (validWlPoints.length > 0) {
		// 绘制填充区域
		ctx.setFillStyle('rgba(33, 150, 243, 0.1)')
		ctx.beginPath()
		ctx.moveTo(validWlPoints[0].x, validWlPoints[0].y)
		validWlPoints.forEach(point => {
			ctx.lineTo(point.x, point.y)
		})
		// 闭合到底部
		ctx.lineTo(validWlPoints[validWlPoints.length - 1].x, flowTop + flowHeight)
		ctx.lineTo(validWlPoints[0].x, flowTop + flowHeight)
		ctx.closePath()
		ctx.fill()
	}

	// 2. 绘制流量和水位折线
	const drawSeries = (arr, color, toY, lineWidth = 2) => {
		// 绘制折线
		ctx.setStrokeStyle(color)
		ctx.setLineWidth(lineWidth)
		ctx.beginPath()
		let hasPrev = false
		
		arr.forEach((val, index) => {
			if (Number.isFinite(val)) {
				const x = padding.left + xStep * index
				const y = toY(val)
				if (!hasPrev) {
					ctx.moveTo(x, y)
					hasPrev = true
				} else {
					ctx.lineTo(x, y)
				}
			}
		})
		ctx.stroke()

		// 绘制数据点
		arr.forEach((val, index) => {
			if (Number.isFinite(val)) {
				const x = padding.left + xStep * index
				const y = toY(val)
				ctx.setFillStyle(color)
				ctx.beginPath()
				ctx.arc(x, y, 3, 0, 2 * Math.PI)
				ctx.fill()
			}
		})
	}

	// 入库流量（蓝色）
	drawSeries(inflowArr, CHART_COLORS.INFLOW, flowToY, 2)
	// 出库流量（绿色）
	drawSeries(outflowArr, CHART_COLORS.OUTFLOW, flowToY, 2)
	// 水位（红色，稍粗）
	drawSeries(wlArr, CHART_COLORS.WATER_LEVEL, wlToY, 2.5)
}

function drawLegend(ctx, padding, canvasWidth, flowTop) {
	// 图例位置：流量图顶部右侧，更紧凑的布局
	const legends = [
		{ label: '入库', color: CHART_COLORS.INFLOW },
		{ label: '出库', color: CHART_COLORS.OUTFLOW },
		{ label: '水位', color: CHART_COLORS.WATER_LEVEL }
	]
	
	const lineLength = 15
	const gap = 4
	const itemGap = 10
	
	// 计算总宽度
	ctx.setFontSize(9)
	let totalWidth = 0
	legends.forEach((item, index) => {
		const textWidth = ctx.measureText(item.label).width || 20
		totalWidth += lineLength + gap + textWidth
		if (index < legends.length - 1) totalWidth += itemGap
	})
	
	// 从右侧开始绘制
	let currentX = canvasWidth - padding.right - totalWidth
	const legendY = flowTop + 8
	
	ctx.setTextAlign('left')
	
	legends.forEach((item, index) => {
		// 绘制线条
		ctx.setStrokeStyle(item.color)
		ctx.setLineWidth(2)
		ctx.beginPath()
		ctx.moveTo(currentX, legendY)
		ctx.lineTo(currentX + lineLength, legendY)
		ctx.stroke()
		
		// 绘制文字
		ctx.setFillStyle(item.color)
		ctx.fillText(item.label, currentX + lineLength + gap, legendY + 3)
		
		// 移动到下一个图例项
		const textWidth = ctx.measureText(item.label).width || 20
		currentX += lineLength + gap + textWidth + itemGap
	})
}

function drawTouchIndicator(ctx, padding, rainfallTop, flowTop, flowHeight, xStep, index) {
	// 计算指示线的 x 坐标
	const x = padding.left + xStep * index
	
	// 绘制贯穿两个图表的竖线
	ctx.setStrokeStyle('rgba(0, 0, 0, 0.5)')
	ctx.setLineWidth(2)
	ctx.setLineDash([5, 5])
	
	// 从降雨图顶部到流量图底部
	ctx.beginPath()
	ctx.moveTo(x, rainfallTop)
	ctx.lineTo(x, flowTop + flowHeight)
	ctx.stroke()
	
	ctx.setLineDash([])
}

// ==================== 生命周期与监听 ====================
onMounted(async () => {
	initCanvasSize()
	await fetchLatestInfo()
	nextTick(() => {
		if (activeTab.value === 'chart') {
			// 先获取流域面，后初始化地图，减少竞态
			fetchBasinGeometry()
			initChartMap()
		}
	})
})

// 标签切换监听
watch(activeTab, (tab) => {
	 if (tab === 'chart') {
		nextTick(() => {
			setTimeout(() => {
				initChartMap()
				addBasinLayer()
			}, 100)
		})
	} else if (tab === 'main') {
		// 等待 DateTimePicker 组件初始化完成后再调用接口
		nextTick(() => {
			setTimeout(() => {
				// 检查时间数据是否已初始化
				if (mainStartDate.value.year && mainEndDate.value.year) {
					fetchWaterData()
				}
			}, 200)
		})
	} else if (tab === 'updown') {
		// 等待 DateTimePicker 组件初始化完成
		nextTick(() => {
			setTimeout(() => {
				if (updownDate.value.year) {
					fetchStreamDataAtTime('rsvr')
				}
			}, 200)
		})
	} else if (tab === 'river') {
		// 等待 DateTimePicker 组件初始化完成
		nextTick(() => {
			setTimeout(() => {
				if (riverDate.value.year) {
					fetchStreamDataAtTime('river')
				}
			}, 200)
		})
	}
})

watch(() => props.stationCode, () => {
	nextTick(() => {
		fetchBasinGeometry()
		addBasinLayer()
		addOutletLayer()
	})
})
</script>
<style scoped>
.water-info-container {
	background: #f5f7fa;
	min-height: 100vh;
	padding: 12rpx;
}

/* 顶部数据区域（对齐图1） */
.top-data-section {
	background: #ffffff;
	border: 1rpx solid #e9edf3;
	border-radius: 12rpx;
	padding: 20rpx 16rpx;
	margin-bottom: 12rpx;
	box-shadow: 0 4rpx 12rpx rgba(31,45,61,0.06);
}

.main-data {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.main-header { display: flex; justify-content: space-between; align-items: center; }
.meta-column { display: flex; flex-direction: column; gap: 12rpx; min-width: 0; }
.meta-row { display: flex; align-items: baseline; gap: 8rpx; flex-wrap: nowrap; }
.meta-label { font-size: 24rpx; color: #666; }
.meta-value { font-size: 28rpx; font-weight: 600; color: #333; }

.level-column {
	display: flex;
	flex-direction: column;
	gap: 12rpx;
	padding-bottom: 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.value-with-unit {
	display: inline-flex;
	align-items: baseline;
	gap: 8rpx;
}

.top-data-section .main-value {
	font-size: 72rpx;
	font-weight: 700;
	color: #d32f2f;
	line-height: 1;
}

.top-data-section .main-unit {
	font-size: 28rpx;
	color: #6b7a90;
	margin-top: 0;
}

.badge-row {
	display: inline-flex;
	align-items: center;
	gap: 10rpx;
}

.badge {
	display: inline-flex;
	align-items: center;
	gap: 8rpx;
	padding: 8rpx 14rpx;
	border-radius: 999rpx;
	font-size: 24rpx;
	line-height: 1;
}

.badge-rise {
	background: #ffecee;
	color: #d62828;
}

.badge-flat {
	background: #eaf2ff;
	color: #1976d2;
}

.badge-fall {
	background: #fff2f2;
	color: #d62828;
}

.badge-icon {
	font-weight: 600;
}

.badge-value, .badge-text {
	font-weight: 600;
}

.data-grid.two-col {
	display: flex;
	flex-direction: column;
	gap: 10rpx;
	width: 100%;
}

.data-row {
	display: grid;
	grid-template-columns: auto 1fr auto 1fr;
	align-items: baseline;
	column-gap: 16rpx;
	row-gap: 8rpx;
}

.data-row .label {
	color: #666;
	white-space: nowrap;
	font-size: 24rpx;
}

.data-row .value-inline {
	display: inline-flex;
	align-items: baseline;
	gap: 4rpx;
	min-width: 0;
}

.data-row .value {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
	white-space: nowrap;
}

.data-row .small-unit {
	font-size: 20rpx;
	color: #999;
	white-space: nowrap;
	flex-shrink: 0;
}

/* 标签栏区域 */
.tab-section {
	background: white;
	border-radius: 12rpx;
	padding: 16rpx 12rpx;
	margin-bottom: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.tab-bar {
	display: flex;
	gap: 0;
}

.tab-item {
	flex: 1;
	text-align: center;
	padding: 16rpx 0;
	border-bottom: 3rpx solid transparent;
	transition: all 0.3s ease;
}

.tab-item.active {
	border-bottom-color: #4a90e2;
}

.tab-text {
	font-size: 28rpx;
	color: #666;
	transition: color 0.3s ease;
}

.data-row .value {
	font-size: 30rpx;
	font-weight: 600;
}

.tab-item.active .tab-text {
	color: #4a90e2;
	font-weight: 600;
}

/* 时间选择器 */
.time-selector {
	background: white;
	border-radius: 12rpx;
	padding: 16rpx 16rpx;
	margin-bottom: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.card-header {
	margin-bottom: 16rpx;
}

.card-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.card-content {
	display: block;
}

.date-picker-row {
	display: flex;
	flex-direction: row;
	align-items: flex-end;     /* 与按钮底部对齐 */
	gap: 20rpx;
	flex-wrap: nowrap;         /* 强制同一行 */
	width: 100%
}

.date-picker-item {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
	flex: 1;            /* 根据内容自适应 */
	min-width: 200rpx;
}

.date-label {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

.datetime-picker {
	display: flex;
	gap: 8rpx;
	align-items: center;
}

.picker-input {
	flex: 1;
	border: 1rpx solid #ddd;
	border-radius: 8rpx;
	overflow: hidden;
}

.date-picker {
	flex: 2;
}

.hour-picker {
	flex: 1;
}

.picker-display {
	padding: 16rpx 20rpx;
	font-size: 28rpx;
	color: #333;
	background: #f8f9fa;
	text-align: center;
}

.query-button-item {
	margin-top: 16rpx;
}

.query-button {
	width: auto;               /* 不再占满整行 */
	padding: 12rpx 24rpx;
	background: #4a90e2;
	color: #fff;
	border: none;
	border-radius: 8rpx;
	font-size: 28rpx;
	font-weight: 500;
}

.query-button:disabled {
	background: #ccc;
	color: #999;
}

/* 该小时水情 */
.current-hour-section {
	background: white;
	border-radius: 12rpx;
	padding: 20rpx 24rpx;
	margin-bottom: 16rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.current-hour-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
}

.current-hour-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.current-time {
	font-size: 28rpx;
	color: #4a90e2;
	font-weight: 500;
}

.export-icon {
	font-size: 32rpx;
	color: #666;
}

.current-hour-data {
	display: flex;
	gap: 0;
}

.hour-data-item {
	flex: 1;
	text-align: center;
	padding: 16rpx 8rpx;
}

.hour-value {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	display: block;
	margin-bottom: 8rpx;
}

.hour-label {
	font-size: 24rpx;
	color: #666;
}

/* 图表区域 */
.chart-section {
	background: white;
	border-radius: 12rpx;
	padding: 16rpx 12rpx;
	margin-bottom: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.chart-labels {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
}

.chart-label-left {
	font-size: 24rpx;
	color: #666;
}

.chart-label-right {
	font-size: 24rpx;
	color: #FF5722;
}

.combined-chart {
	width: 100%;
	height: 560rpx;
	position: relative;
}

.chart-canvas {
	width: 100%;
	height: 100%;
}

.chart-bottom-label {
	margin-top: 16rpx;
}

/* 新增：简易日期条（图1/图2头部） */
.simple-date-bar {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	gap: 12rpx;
	padding: 16rpx 16rpx;
	background: #ffffff;
	border-radius: 12rpx;
	margin-bottom: 12rpx;
}

.date-separator {
	font-size: 26rpx;
	color: #666;
	padding: 0 8rpx;
}

.datetime-picker-wrapper {
	display: inline-block;
}

.date-chip-picker {
	display: inline-flex;
	align-items: center;
	gap: 8rpx;
	background: #ffffff;
	border: 1rpx solid #e9edf3;
	border-radius: 12rpx;
	padding: 10rpx 16rpx;
	white-space: nowrap;
}

.date-chip-text {
	color: #3c4353;
	font-size: 26rpx;
}

.date-chip {
	background: #ffffff;
	border: 1rpx solid #e9edf3;
	border-radius: 12rpx;
	padding: 10rpx 16rpx;
	color: #3c4353;
	font-size: 26rpx;
}

.dropdown-icon {
	color: #9aa0a6;
	font-size: 24rpx;
	margin-left: 12rpx;
}

/* 新增：汇总卡片（图1三卡、图2四卡） */
.summary-cards {
	display: grid;
	gap: 16rpx;
	margin: 12rpx 20rpx 20rpx;
}
.summary-cards.three { grid-template-columns: repeat(3, 1fr); }
.summary-cards.four  { grid-template-columns: repeat(4, 1fr); }

.summary-card {
	background: linear-gradient(180deg, #f9fbff 0%, #eef3fb 100%);
	border: 1rpx solid #e1e8f5;
	border-radius: 14rpx;
	padding: 18rpx;
	text-align: center;
	box-shadow: 0 4rpx 12rpx rgba(31,45,61,0.06);
}
.summary-value {
	font-size: 34rpx;
	color: #2c7be5;
	font-weight: 600;
}
.summary-label {
	display: block;
	margin-top: 8rpx;
	font-size: 22rpx;
	color: #7b8794;
}

/* 新增：表格区域（图1/图2列表） */
.table-section {
	background: #ffffff;
	border: 1rpx solid #e9edf3;
	border-radius: 16rpx;
	margin: 0 20rpx 24rpx;
	overflow: hidden;
}

.table-header, .table-row {
	display: grid;
	grid-template-columns: 2.2fr 1.2fr 1.2fr 1.2fr 1.2fr;
	padding: 16rpx 20rpx;
}
.table-header {
	background: #f6f8fb;
	color: #7b8794;
	font-size: 22rpx;
}

.th {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	gap: 4rpx;
	text-align: center;
}

.th-unit {
	font-size: 20rpx;
	color: #999;
}

.table-row {
	border-top: 1rpx solid #eef1f6;
	color: #3c4353;
	font-size: 24rpx;
}

.td {
	text-align: center;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.expand-bar {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 12rpx;
	padding: 16rpx 20rpx;
	color: #7b8794;
	font-size: 22rpx;
	border-top: 1rpx dashed #e9edf3;
}
.expand-action { color: #2c7be5; }
.expand-arrow  { color: #9aa0a6; }

/* ==================== 主水库标签页样式 ==================== */
.main-reservoir-section {
	padding: 0;
}

/* 水情情势卡片 */
.water-situation-card {
	background: #ffffff;
	border-radius: 12rpx;
	padding: 20rpx 16rpx 16rpx;
	margin-bottom: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.situation-title {
	font-size: 30rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 16rpx;
	display: block;
}

.situation-grid {
	display: flex;
	justify-content: space-between;
	align-items: center;
	gap: 20rpx;
}

.situation-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8rpx;
}

.situation-label {
	font-size: 24rpx;
	color: #999;
	line-height: 1.2;
}

.situation-value-row {
	display: flex;
	align-items: baseline;
	gap: 4rpx;
	flex-wrap: wrap;
}

.situation-value {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	line-height: 1.2;
}

.situation-unit {
	font-size: 20rpx;
	color: #666;
	line-height: 1.2;
}

/* 该小时水情卡片 */
.hour-water-info-card {
	background: #ffffff;
	border-radius: 12rpx;
	padding: 20rpx 24rpx;
	margin-bottom: 16rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.hour-header-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 16rpx;
}

.hour-title {
	font-size: 30rpx;
	font-weight: 600;
	color: #333;
}

.hour-time {
	font-size: 26rpx;
	color: #4a90e2;
	font-weight: 500;
}

.export-btn {
	padding: 4rpx 8rpx;
}

.export-icon {
	font-size: 28rpx;
	color: #666;
}

.hour-data-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 16rpx;
}

.hour-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8rpx;
	min-width: 0;
}

.hour-value-text {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	line-height: 1.2;
}

.hour-label-wrapper {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 2rpx;
	text-align: center;
}

.hour-label-text {
	font-size: 24rpx;
	color: #666;
	line-height: 1.3;
	white-space: nowrap;
}

.hour-unit-text {
	font-size: 20rpx;
	color: #999;
	line-height: 1.2;
	white-space: nowrap;
}

/* 图表容器 */
.main-chart-container {
	background: #ffffff;
	border-radius: 12rpx;
	padding: 20rpx 24rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.chart-canvas-wrapper {
	width: 100%;
	height: auto;
	min-height: 480rpx;
	position: relative;
	overflow: visible;
}

.main-chart-canvas {
	width: 100%;
	height: 100%;
	display: block;
}

/* 地图区域样式 */
.map-container { 
	width: 100%; 
	height: 100%; 
	border-radius: 12rpx; 
	overflow: hidden; 
	background: #f5f5f5; 
}

.leaflet-map { 
	width: 100%; 
	height: 100%;
	min-height: 800rpx; 
	border-radius: 12rpx; 
}

.map-not-supported { 
	padding: 24rpx; 
	text-align: center; 
	color: #6c757d; 
}
</style>